<template>
  <view class="contact-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">紧急联系人</text>
      <u-button 
        type="primary" 
        size="small" 
        @click="showAddContact"
        :customStyle="{ backgroundColor: '#2d8cf0' }"
      >
        添加联系人
      </u-button>
    </view>
    
    <!-- 联系人列表 -->
    <view class="contact-list" v-if="contactList.length > 0">
      <view 
        class="contact-item" 
        v-for="(contact, index) in contactList" 
        :key="contact.id"
        @click="editContact(contact)"
      >
        <view class="contact-avatar">
          <u-avatar 
            :src="contact.avatar || '/static/images/default-avatar.png'"
            size="50"
          />
        </view>
        <view class="contact-info">
          <view class="contact-name">
            <text class="name">{{ contact.name }}</text>
            <text class="relation" v-if="contact.relation">({{ contact.relation }})</text>
          </view>
          <view class="contact-phone">{{ contact.phone }}</view>
          <view class="contact-address" v-if="contact.address">{{ contact.address }}</view>
        </view>
        <view class="contact-actions">
          <u-button 
            type="primary" 
            size="mini" 
            @click.stop="callContact(contact)"
            :customStyle="{ backgroundColor: '#07c160' }"
          >
            拨打
          </u-button>
          <u-button 
            type="error" 
            size="mini" 
            @click.stop="deleteContact(contact)"
            :customStyle="{ backgroundColor: '#ff4757' }"
          >
            删除
          </u-button>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <u-empty 
        text="暂无紧急联系人" 
        mode="list"
        :icon="emptyIcon"
      >
        <u-button 
          type="primary" 
          @click="showAddContact"
          :customStyle="{ backgroundColor: '#2d8cf0' }"
        >
          添加第一个联系人
        </u-button>
      </u-empty>
    </view>
    
    <!-- 添加/编辑联系人弹窗 -->
    <u-popup 
      v-model="showContactForm" 
      mode="center" 
      :round="10"
      :closeable="true"
    >
      <view class="contact-form">
        <view class="form-header">
          <text class="form-title">{{ isEdit ? '编辑联系人' : '添加联系人' }}</text>
        </view>
        
        <u-form :model="contactForm" ref="formRef" :rules="formRules">
          <u-form-item prop="name" label="姓名">
            <u-input 
              v-model="contactForm.name"
              placeholder="请输入联系人姓名"
              :border="false"
              :customStyle="inputStyle"
            />
          </u-form-item>
          
          <u-form-item prop="phone" label="手机号">
            <u-input 
              v-model="contactForm.phone"
              placeholder="请输入手机号"
              type="number"
              :border="false"
              :customStyle="inputStyle"
            />
          </u-form-item>
          
          <u-form-item prop="relation" label="关系">
            <u-input 
              v-model="contactForm.relation"
              placeholder="请输入关系（如：父亲、母亲、配偶等）"
              :border="false"
              :customStyle="inputStyle"
            />
          </u-form-item>
          
          <u-form-item prop="address" label="地址">
            <u-input 
              v-model="contactForm.address"
              placeholder="请输入地址（可选）"
              :border="false"
              :customStyle="inputStyle"
            />
          </u-form-item>
          
          <u-form-item prop="isEmergency" label="紧急联系人">
            <u-switch 
              v-model="contactForm.isEmergency"
              activeColor="#2d8cf0"
            />
          </u-form-item>
        </u-form>
        
        <view class="form-actions">
          <u-button 
            type="default" 
            @click="cancelContact"
            :customStyle="{ flex: 1, marginRight: '10px' }"
          >
            取消
          </u-button>
          <u-button 
            type="primary" 
            @click="saveContact"
            :loading="saveLoading"
            :customStyle="{ flex: 1, backgroundColor: '#2d8cf0' }"
          >
            {{ saveLoading ? '保存中...' : '保存' }}
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
/**
 * 紧急联系人页面
 * @author Wu.Liang
 * @date 2025-01-21
 */

import { ref, reactive, onMounted, computed } from 'vue'
import { useUserStore } from '@/store'

const userStore = useUserStore()
const formRef = ref(null)
const showContactForm = ref(false)
const saveLoading = ref(false)
const isEdit = ref(false)
const currentContact = ref(null)

// 空状态图标
const emptyIcon = 'list'

// 联系人列表
const contactList = ref([
  {
    id: 1,
    name: '张三',
    phone: '13800138000',
    relation: '父亲',
    address: '北京市朝阳区',
    isEmergency: true,
    avatar: ''
  },
  {
    id: 2,
    name: '李四',
    phone: '13900139000',
    relation: '母亲',
    address: '北京市海淀区',
    isEmergency: true,
    avatar: ''
  }
])

// 表单数据
const contactForm = reactive({
  name: '',
  phone: '',
  relation: '',
  address: '',
  isEmergency: true
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入联系人姓名' },
    { min: 2, message: '姓名长度不能少于2位' }
  ],
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
  ],
  relation: [
    { required: true, message: '请输入关系' }
  ]
}

// 输入框样式
const inputStyle = computed(() => ({
  backgroundColor: '#f8f9fa',
  borderRadius: '8px',
  padding: '12px 16px',
  fontSize: '16px',
  height: '48px'
}))

// 显示添加联系人弹窗
const showAddContact = () => {
  isEdit.value = false
  currentContact.value = null
  resetForm()
  showContactForm.value = true
}

// 编辑联系人
const editContact = (contact) => {
  isEdit.value = true
  currentContact.value = contact
  contactForm.name = contact.name
  contactForm.phone = contact.phone
  contactForm.relation = contact.relation
  contactForm.address = contact.address || ''
  contactForm.isEmergency = contact.isEmergency
  showContactForm.value = true
}

// 重置表单
const resetForm = () => {
  contactForm.name = ''
  contactForm.phone = ''
  contactForm.relation = ''
  contactForm.address = ''
  contactForm.isEmergency = true
}

// 取消操作
const cancelContact = () => {
  showContactForm.value = false
  resetForm()
}

// 保存联系人
const saveContact = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    saveLoading.value = true
    
    if (isEdit.value) {
      // 编辑联系人
      const index = contactList.value.findIndex(item => item.id === currentContact.value.id)
      if (index !== -1) {
        contactList.value[index] = {
          ...currentContact.value,
          ...contactForm
        }
      }
      uni.showToast({
        title: '联系人更新成功',
        icon: 'success'
      })
    } else {
      // 添加联系人
      const newContact = {
        id: Date.now(),
        ...contactForm,
        avatar: ''
      }
      contactList.value.push(newContact)
      uni.showToast({
        title: '联系人添加成功',
        icon: 'success'
      })
    }
    
    showContactForm.value = false
    resetForm()
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  } finally {
    saveLoading.value = false
  }
}

// 拨打联系人电话
const callContact = (contact) => {
  uni.showModal({
    title: '拨打电话',
    content: `是否拨打 ${contact.name} 的电话？`,
    success: (res) => {
      if (res.confirm) {
        uni.makePhoneCall({
          phoneNumber: contact.phone,
          fail: (err) => {
            uni.showToast({
              title: '拨打失败',
              icon: 'none'
            })
          }
        })
      }
    }
  })
}

// 删除联系人
const deleteContact = (contact) => {
  uni.showModal({
    title: '删除联系人',
    content: `确定要删除联系人 ${contact.name} 吗？`,
    success: (res) => {
      if (res.confirm) {
        const index = contactList.value.findIndex(item => item.id === contact.id)
        if (index !== -1) {
          contactList.value.splice(index, 1)
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
        }
      }
    }
  })
}

// 页面加载
onMounted(() => {
  // 这里可以调用API获取联系人列表
  console.log('紧急联系人页面加载完成')
})
</script>

<style lang="scss" scoped>
.contact-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.contact-list {
  .contact-item {
    display: flex;
    align-items: center;
    padding: 30rpx;
    margin-bottom: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    
    .contact-avatar {
      margin-right: 20rpx;
    }
    
    .contact-info {
      flex: 1;
      
      .contact-name {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;
        
        .name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
        }
        
        .relation {
          font-size: 24rpx;
          color: #666;
          margin-left: 10rpx;
        }
      }
      
      .contact-phone {
        font-size: 28rpx;
        color: #2d8cf0;
        margin-bottom: 8rpx;
      }
      
      .contact-address {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .contact-actions {
      display: flex;
      flex-direction: column;
      gap: 10rpx;
    }
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400rpx;
}

.contact-form {
  width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  
  .form-header {
    text-align: center;
    margin-bottom: 40rpx;
    
    .form-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .form-actions {
    display: flex;
    margin-top: 40rpx;
    gap: 20rpx;
  }
}
</style> 